<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet_2_0"%>
<%@ taglib prefix="liferay-theme" uri="http://liferay.com/tld/theme"%>
<%@ taglib prefix="liferay-portlet" uri="http://liferay.com/tld/portlet"%>
<%@ page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@ page import="com.liferay.portal.util.PortalUtil"%>
<%@ page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
 
<portlet:defineObjects />
<liferay-theme:defineObjects/>
<portlet:resourceURL id='exportTable' var='exportTable' />

<portlet:resourceURL var="resourceURL" escapeXml="false" id="resourceURLID"></portlet:resourceURL>

<%
String contextPath = request.getContextPath();
String serverKey="";
if (themeDisplay.getScopeGroup().getExpandoBridge().hasAttribute("server_key")) {
  serverKey = themeDisplay.getScopeGroup().getExpandoBridge().getAttribute("server_key").toString();
}
if (serverKey.isEmpty()) {
	serverKey = "http://127.0.0.1:8090/";
}
%>
<script type="text/javascript" src="<%=contextPath%>/js/moment.js"></script>
<script type="text/javascript">
    var context = {
        path: '<%=contextPath%>/',
        ajaxURL : '${resourceURL}',
        base: '<%=contextPath%>/pages/employee/',
        jsPath: '${themeDisplay.getPathThemeJavaScript()}',
        action: {
        	countEmployeeByDay: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/employee/day',
        	countEmployeeByMonth: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/employee/month',
        	countEmployeeByYear: '<%=contextPath%>/jsonActionProxy?serverKey=<%=serverKey%>&hostUrl=mis-server/rest/report/employee/year',        
        },
        userId: <%=user.getUserId()%>,
        companyId: <%=user.getCompanyId()%>
    };
</script>

<style>
#contain {
    overflow: auto;
}

#reportTable tr th {
    background-color: #f2f2f2;
}

#reportTable tr:nth-of-type(odd) {
    background-color: #FFF;
}

#reportTable tr:nth-of-type(even) {
    background-color: #f2f2f2;
}

#reportTable .sum {
    font-weight: bold;
}

#reportTable td:nth-child(2)  {
	white-space: nowrap;
}

.layui-table-cell{
 	height: auto;
    white-space: normal;
}
.layui-card-header {
	display: none;
}

html {
  overflow-y:hidden;
}

#contain {
  overflow-y: scroll;
  /*height: 100%;*/
}

#reportTable {
  overflow-y:hidden;
}

#reportTable tr td, #reportTable tr th {
  color: #111;
}

#reportTable tr.warning {
	background: #FF5733;
}
</style>

<div id="contain">
    <table class="layui-table" id="reportTable">
    </table>
</div>
<script>
function keepTwoDecimal(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
        return false;
    }
    result = Math.round(num * 100) / 100;
    return result;
}

function genTableForDay(data, fromDate, toDate) {

    var head = '<tr><th>工号</th><th>员工</th><th>' + fromDate + '</th><th>' + toDate + '</th></tr>';
    var thead = "<thead>" + head + "</thead>";
	    
    var start = moment(fromDate);

    // data
    var employee = [];
    var lines = '';
    var dateHourObj = {};
    for (var i = 0; i < data.length; i++) {
        var row = data[i];

        var line = "<tr {0}><td>" + row.employeeNumber + "</td><td>" + row.employeeName + "</td>";
        var marked = false;

        start = moment(new Date(fromDate));
        end = moment(new Date(toDate));

        while (start.isBefore(end) || start.isSame(end)) {

            var curDate = start.format('YYYY-MM-DD');
            var dates = row.workDateList;
            if (row.workDateList.indexOf(curDate) == -1) {
                line += '<td>0</td>';
            } else {
                dates.forEach(function(item, index) {
                    if (item == curDate) {
                    	if (!marked && parseFloat(row.workHourList[index]) >= 12) {
                    		var cls = 'class="warning"';
                    		marked = true;
                    		line = line.replace('\{0\}', cls);
	                	}
	                	if (parseFloat(row.workHourList[index]) >= 12) {
	                		line += '<td style="font-weight:bold">' + row.workHourList[index] + '</td>';
	                	} else {
	                    	line += '<td>' + row.workHourList[index] + '</td>';
	                	}                    	
                        typeof dateHourObj[curDate] == "undefined" ? (dateHourObj[curDate] = row.workHourList[index]) : (dateHourObj[curDate] += row.workHourList[index]);
                        return;
                    }
                });
            }

            start.add(1, 'day');
        }
        
        line += '</tr>';
        lines += line;
    }

    var totalLine = '<tr class="sum"><td colspan=2>合计(小时)</td>';
    start = moment(new Date(fromDate));
    end = moment(new Date(toDate));
    var total = 0;

    while (start.isBefore(end) || start.isSame(end)) {
        var curDate = start.format('YYYY-MM-DD');
        if (dateHourObj[curDate] != undefined) {
            total += dateHourObj[curDate];
            totalLine += '<td>' + keepTwoDecimal(dateHourObj[curDate]) + '</td>';
        } else {
            totalLine += '<td>0</td>';
        }
        start.add(1, 'day');
    }
    
    totalLine += '</tr>';
    
	var tbody = "<tbody>" + lines + totalLine + "</tbody>";
    
    var str = thead + tbody;
    $('#reportTable').html(str);
}

// 显示昨天和今天的统计
function queryUserReport() {
	
	var toDate = moment(new Date()).format('YYYY-MM-DD');
	var fromDate = moment(new Date()).subtract(1, 'day').format('YYYY-MM-DD');
    var url = context.action.countEmployeeByDay + '?fromDate=' + fromDate + '&toDate=' + toDate;

    $.ajax({
        url: url,
        type: "GET",
        success: function(rsp) {
            if (rsp.success || rsp.code == 0) {
                console.dir(rsp.data);

                genTableForDay(rsp.data, fromDate, toDate);
                
                docHeight = $(document).height() - 30;
          	  	$('#contain').css('height', docHeight + 'px');
          	 
          	    setTimeout('pageScroll()', 1050);

            } else {
                Lib.error(rsp.msg || '提交失败');
            }
        },
        error: function(rsp) {
            Lib.error(rsp.msg || '提交失败');
        }
    });
}

var docHeight = 0, oldDocHeight = 0;
var scrollTimer = null, interval = 200, maxMills = 60000, times = 0;

function pageScroll() {
	
  var objDiv = document.getElementById("contain");
  objDiv.scrollTop = objDiv.scrollTop + 2;  
  
  var top = objDiv.scrollTop;

  // no need scroll
  if (top == 0) {
	  
    if (interval * times >= maxMills) {
      location.reload();
    }
    
  } else {
	  
	 if (oldDocHeight > 0 && top == oldDocHeight) {
		// already scroll to bottom
		
		if (interval * times >= maxMills) {
		   location.reload();
		}

		objDiv.scrollTop = 0;
		oldDocHeight = 0;
		
	 } else {
		oldDocHeight = objDiv.scrollTop;
	 }  
  }
  
  ++times;

  scrollTimer = setTimeout('pageScroll()', interval);
}

layui.use(['layer'], function(module) {
	queryUserReport();
});


</script>